const host = 'http://localhost:3000'


function btn_Add() {
    console.log('新增');
    location.href = './AddOrEdit.html'

}

function btn_filter() {
    /**
     * 1. 拿数据
     * 2. 发送请求
     * 3. 根据请求返回相应的处理
     */

    let keyword = $('[name=keyword]').val()

    axios.get(`${host}/blogs?keyword=${keyword}`).then((res) => {
        //清空列表数据
        $('tr[class^=blog]').remove()

        //插入过滤后的数据
        res.data.data.forEach(item => {
            let html = `
            <tr class="blog${item.id}">
              <td>${item.id}</td>
              <td>${item.title}</td>
              <td>${item.author}</td>
              <td>
                  <input type="button" value="编辑" onclick="btn_Edit(${item.id})">
                  <input type="button" value="删除" onclick="btn_Del(${item.id})">
              </td>
          </tr>
      `

            $('tbody').append(html)
        })
    })


}

function btn_Edit(id) {
    console.log('编辑');
    location.href = './AddOrEdit.html?id=' + id;

}
function btn_Del(id) {
    if (confirm('确认删除吗？ ')) {
        axios.delete(`${host}/blogs/${id}`).then((res) => {
            if (res.data.code === 1000) {
                $(`.blog${id}`).remove()
            }
            console.log(id);

        })
    }
}

async function btn_Save() {
    console.log('保存');

    let id = new URLSearchParams(location.search).get('id') || 0;
    //获取数据
    const title = $('[name=title]').val()
    const author = $('[name=author]').val()


    let res;
    if (id) {
        res = await axios.put(`${host}/blogs/${id}`, { title, author })  //有id，编辑
    } else {
        res = await axios.post(`${host}/blogs`, { title, author })  //没有id，新增
    }

    if (res.data.code === 1000) {
        location.href = './blogs.html'
    }

}

function btn_Cancel() {
    console.log("取消");
    location.href = './blogs.html'
}
